<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/11 0011
 * Time: 16:20
 */

namespace Cohuna\Controllers;

use Cohuna\Models\CohunaMerchant;
use Cohuna\Models\CohunaMerchantPay;
use Cohuna\Models\CohunaPay;
use Cohuna\Paginator\PaginatorArray;
use Cohuna\Services\CommonService;

/**
 * 应用管理
 * @package Cohuna\Controllers
 */
class MerchantController extends ControllerBase
{
    public function indexAction()
    {
        exit(CommonService::getInstance()->createSerialNumber());
    }
    /**
     * 商户列表
     */
    public function listAction()
    {
        $page = max(intval($this->request->getQuery('page')),1);

        $offset = ($page - 1) * self::PageSize;

        $list = CohunaMerchant::find(array(
            'id > 0',
            'offset' => intval($offset),
            'limit' => self::PageSize,
            'order' => 'id DESC'
        ));

        $paginator = new PaginatorArray([
            'data'          => $list,
            'limit'         => self::PageSize,
            'current'          => $page,
            'total_items'   => CohunaMerchant::count(),
            'href'          => '/merchant/list'
        ]);
        $this->view->setVar('Model',$paginator);
    }

    /**
     * 商户详情
     */
    public function detailAction()
    {
        $merchant_id = trim($this->request->getQuery('mch_id'));
        if(empty($merchant_id) === false){
            $merchant = CohunaMerchant::findFirstByMerchantId($merchant_id);

        }
        if(!isset($merchant)){
            $this->dispatcher->forward(array('controller'=>'Error','action'=>'show404'));
            return;
        }
        $pay_list = CohunaPay::findByMerchantId($merchant_id);

        $this->view->setVar('PayList',$pay_list);
        $this->view->setVar("Model",$merchant);
        $this->view->setVar('Gateway', $this->config->app->baseUri . 'gateway.do');
        $this->view->setVar('RsaPublicCert',file_get_contents($this->config->certificate->rsa_public_key_path));
    }

    /**
     * 编辑商户信息
     */
    public function editAction()
    {
        $merchant_id = trim($this->request->getQuery('mch_id'));
        $merchant = new CohunaMerchant();
        $merchant->merchant_status = 'y';
        if(empty($merchant_id) === false){
            $merchant = CohunaMerchant::findFirstByMerchant_id($merchant_id);
            if(empty($merchant)){
                $this->dispatcher->forward(array('controller'=>'Error','action'=>'show404'));
            }
        }
        if($this->request->isPost()){
            $merchant_id = trim($this->request->getQuery('merchant_id'));
            $merchant_status = trim($this->request->getPost('merchant_status'));
            $merchant_name = trim($this->request->getPost('merchant_name'));
            $merchant_images = $this->request->getUploadedFiles(true);
            $remark = trim($this->request->getPost('remark'));

            if(empty($merchant_name) || strlen($merchant_name) > 200){
                $this->view->setVar('ErrorMessage','商户名称不能为空且必须小于200字符');
                return;
            }
            if(empty($remark) === false && strlen($remark) > 1000){
                $this->view->setVar('ErrorMessage','商户简介必须小于1000字符');
                return;
            }

            if(empty($merchant_id) === false){
                $merchant = CohunaMerchant::findFirstByMerchant_id($merchant_id);
                if(empty($merchant)){
                    $this->view->setVar('ErrorMessage','商户不存在');
                    return;
                }
                $merchant->update_id = 0;
            }else{
                $merchant->merchant_id = CohunaMerchant::createMerchantId();
                $merchant->create_id = 0;
                $merchant->gateway = trim($this->request->getPost('gateway'));
                $merchant->merchant_public_cert = trim($this->request->getPost('merchant_public_cert'));
            }

            if(count($merchant_images) > 0){
                $image_file = $merchant_images[0];
                if($image_file->getSize() > 0){
                    $image_path = PUBLIC_PATH . '/uploads/' . date('Ymd') . '/' . uniqid('mch_') .'.' . $image_file->getExtension();
                    @mkdir(dirname($image_path),0766,true);
                    if($image_file->moveTo($image_path)){
                        $merchant->merchant_image_url = substr($image_path,strlen(PUBLIC_PATH));
                    }
                }
            }

            $merchant->merchant_name = $merchant_name;
            $merchant->merchant_status = $merchant_status == 'y' ? 'y' : 'n';
            $merchant->remark = $remark;

            if($merchant->save()){
                $this->view->setVar('OkMessage','保存成功');
            }else{
                $this->view->setVar('ErrorMessage','保存失败');
            }
        }

        $this->view->setVar("Model",$merchant);

    }

    /**
     * 编辑商户公钥
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function editEncryptionAction()
    {
        $merchant_id = trim($this->request->getPost('merchant_id'));
        $merchant_public_cert = trim($this->request->getPost('merchant_public_cert'));
        if(empty($merchant_public_cert)){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'商户公钥不能为空'))->send();
        }
        if(empty($merchant_id) === false){
            $merchant = CohunaMerchant::findFirstByMerchant_id($merchant_id);
        }
        if(!isset($merchant)){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'商户不存在'))->send();
        }
        $merchant->merchant_public_cert = $merchant_public_cert;
        if($merchant->save()){
            return $this->response->setJsonContent(array('errCode'=>0,'errMsg'=>'保存成功','merchant_public_cert'=>$merchant_public_cert))->send();
        }else{
            return $this->response->setJsonContent(array('errCode'=>50002,'errMsg'=>'保存失败'))->send();
        }
    }

    /**
     * 保存商户网关
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function editGatewayAction()
    {
        $merchant_id = trim($this->request->getPost('merchant_id'));
        $gateway = trim($this->request->getPost('gateway'));

        if(empty($merchant_id) === false){
            $merchant = CohunaMerchant::findFirstByMerchantId($merchant_id);
        }
        if(!isset($merchant)){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'商户不存在'))->send();
        }
        $merchant->gateway = $gateway;
        if($merchant->save()){
            return $this->response->setJsonContent(array('errCode'=>0,'errMsg'=>'保存成功','gateway'=>$gateway))->send();
        }else{
            return $this->response->setJsonContent(array('errCode'=>50002,'errMsg'=>'保存失败'))->send();
        }
    }

    /**
     * 删除商家的支付配置
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function deleteMerchantPayAction()
    {
        $merchant_id = trim($this->request->getPost('merchant_id'));
        $pay_id = trim($this->request->getPost('pay_id'));

        $merchant_pay = CohunaMerchantPay::findFirst(array('merchant_id=:merchant_id: AND pay_id=:pay_id:','bind'=>array('merchant_id'=>$merchant_id,'pay_id'=>$pay_id)));

        if(empty($merchant_pay)){
            return $this->response->setJsonContent(array('errCode' => 50001,'errMsg' => '数据不存在'))->send();
        }elseif($merchant_pay->delete()){
            return $this->response->setJsonContent(array('errCode' => 0,'errMsg' => '删除成功'))->send();
        }else{
            return $this->response->setJsonContent(array('errCode' => 50001,'errMsg' => '删除失败'))->send();
        }
    }
}